<template>
	<el-card shadow="never">
		<el-form
            :inline="true"
            :model="queryForm"
            @keyup.enter="onSearch()">
			<el-form-item>
				<el-input
                    v-model="queryForm.name"
                    placeholder="名称"
                    clearable>
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="onSearch()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleRole()">新增</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="deleteBatch()">删除</el-button>
			</el-form-item>
		</el-form>
        
		<el-table
            border
            v-loading="loading"
            :data="roleList"
            style="width: 100%"
            @selection-change="selectRoleId">
			<el-table-column
                type="selection"
                header-align="center"
                align="center"
                width="50">
            </el-table-column>
			<el-table-column
                prop="name"
                label="名称"
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                prop="remark"
                label="备注"
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                prop="createTime"
                label="创建时间"
                header-align="center"
                align="center"
                width="180">
                <template #default="scope">
                    {{ scope.row.createTime.replace('T', ' ').split('+')[0] }}
                </template>
            </el-table-column>
			<el-table-column
                label="操作"
                fixed="right"
                header-align="center"
                align="center"
                width="200">
				<template #default="scope">
                    <div class="role-actions">
                        <el-button type="primary" link @click="handleRole(scope.row.id)">修改</el-button>
                        <el-button type="primary" link @click="deleteBatch(scope.row.id)">删除</el-button>
                        <el-dropdown style="margin-left: 20px;" @command="(command) => onCommand(command, scope.row)">
                            <el-button type="primary" class="el-dropdown-link" link>更多</el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item command="dataScope">数据权限</el-dropdown-item>
                                    <el-dropdown-item command="user">分配用户</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
				</template>
			</el-table-column>
		</el-table>
        
        <div style="margin-top: 20px">
            <el-pagination
                    layout="prev, pager, next"
                    v-model:current-page="pagination.page"
                    :page-size="pagination.limit"
                    :total="pagination.total"
                    @current-change="onPageChange"
                    background>
            </el-pagination>
        </div>

        <!-- 新增/修改组件 -->
        <RoleDlg ref="roleDlgRef" @refresh="getRolePage" />
		<!-- 分配用户 -->
		<el-drawer
            v-if="userVisible"
            v-model="userVisible"
            :title="userTitle"
            :size="800"
            :close-on-press-escape="false">
			<UserPnl :role-id="roleId" />
		</el-drawer>
		<!-- 数据权限 -->
		<PowerDlg ref="powerDlgRef" />
    </el-card>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue'
import { roleStore } from '@/store/role'
import { ElMessage, ElMessageBox } from 'element-plus'
import RoleDlg from './role_dlg.vue'
import UserPnl from './user_pnl.vue'
import PowerDlg from './power_dlg.vue'

const useRoleStore = roleStore()
// 直接从store获取数据
const roleList = computed(
    () => useRoleStore.roleList
)
const pagination = computed(
    () => useRoleStore.pagination
)
const loading = ref(false)
const queryForm = reactive({
    name: '',
    status: ''
})

onMounted(() => {
    getRolePage()
})

const getRolePage = async() => {
    loading.value = true
    try {
        await useRoleStore.getRolePage(queryForm)
    } catch (error) {
        console.error('获取角色列表失败:', error)}
    finally {
        loading.value = false
    }
}

const onSearch = () => {
    console.log('查询表单数据:', queryForm)    
    // 重置到第一页
    usePostStore.pagination.page = 1
    // 重新获取列表
    getRolePage()
}

const onPageChange = (page) => {
    usePostStore.pagination.page = page
    getRolePage()
}

const roleDlgRef = ref(null) // 新增/修改组件的引用
const handleRole = (id) => {
    if (id) {
        roleDlgRef.value.init(id) // 修改模式
    } else {
        roleDlgRef.value.init() // 新增模式
    }
}

const deleteBatch = async(key) => {
    const ids = key ? [key] : selectedIds.value
    if (ids.length === 0) {
      ElMessage.warning('请选择删除记录')
      return
    }

    try {
        const confirm = await ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        if (confirm === 'confirm') {
            // console.log('删除角色ID:', ids)
            await useRoleStore.deleteBatch(ids)
            ElMessage.success('删除成功')
            await getRolePage() // 刷新列表
        }
    } catch (error) {
        // 用户点击取消或关闭弹窗
        console.log('删除操作已取消')
    }
}

const selectedIds = ref([])
const selectRoleId = (val) => {
    selectedIds.value = val.map(item => item.id)
    // console.log('选中的角色ID:', selectedIds.value)
}

const powerDlgRef = ref()
const userVisible = ref(false)
const roleId = ref()
const userTitle = ref()
const onCommand = (command, row) => {
	if (command === 'dataScope') {
		powerDlgRef.value.init(row.id)
	} else if (command === 'user') {
		roleId.value = row.id
		userTitle.value = '分配用户 - ' + row.name + '(' + row.id + ')'
		userVisible.value = true
	}
}

</script>

<style lang="scss" scoped>
.role-actions {
  display: flex;
  justify-content: center;
}
:deep(.el-drawer__header) {
	height: 50px;
	margin-bottom: 0;
	padding: 0 15px;
    border-bottom: 1px solid var(--el-border-color);
}
</style>